<!-- 添加商品 -->
<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="添加商品信息" type="info" center :closable="false" show-icon></el-alert>
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="goodsForm"
        :rules="goodsRules"
        ref="goodsRef"
        label-position="top"
        label-width="100px"
      >
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforeLeaveTab"
          @tab-click="goodsTabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="goodsForm.name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="goodsForm.price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品描述" prop="descs">
              <el-input type="textarea" :rows="2" placeholder="请输入商品描述" v-model="goodsForm.descs"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="pCategoryId">
              <el-cascader
                v-model="cascaderValue"
                :options="parentCateData"
                :props="cateProps"
                @change="cascaderChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attrVals">
                <el-checkbox :label="item2" v-for="(item2, i2) in item.attrVals" :key="i2" border></el-checkbox>
                <!-- <el-checkbox :label="item2.tag_id" v-for="(item2, i2) in item.attr_vals" :key="i2" border>
                  {{item2.attr_val}}
                </el-checkbox>-->
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attrVals[0]"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              name="fileName"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headersObj"
              list-type="picture"
              :on-success="uploadSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="goodsForm.detail"></quill-editor>
            <el-button type="primary" class="add-btn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- 图片预览 -->
      <el-dialog title="图片预览" :visible.sync="previewVisible">
        <img :src="previewURL" alt="uploadImg" />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// 引入axios接口
import { reqParentCateList, reqCateParams, reqAddGoods } from '@/api'
export default {
  data() {
    // 自定义验证规则
    var validatePrice = (rule, value, callback) => {
      if (value > 0) {
        callback()
      } else {
        callback(new Error('价格必须大于0'))
      }
    }
    return {
      activeIndex: '0', // 默认激活步骤条
      goodsForm: {
        name: '',
        price: 0,
        pCategoryId: '',
        imgsList: [],
        descs: '',
        detail: ''
      },
      goodsRules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { validator: validatePrice, trigger: 'blur' }
        ],
        descs: [{ required: true, message: '请输入商品描述', trigger: 'blur' }]
      },
      parentCateData: [], // 级联选择数据源
      cascaderValue: [], // 级联选择的值
      cateProps: {
        // 设置分类表格展示属性
        expandTrigger: 'hover',
        label: 'name',
        value: 'id'
      },
      manyTableData: [], // 动态参数
      onlyTableData: [], // 静态属性
      tagList: [], // 商品标签数组
      uploadURL: '/api/files/upload.do',
      headersObj: { Authorization: window.sessionStorage.getItem('webToken') },
      previewURL: '', // 预览图片路径
      previewVisible: false // 图片预览对话框
    }
  },

  computed: {
    // 级联选择的分类ID
    cateId() {
      if (this.cascaderValue.length === 3) {
        return this.cascaderValue[2]
      }
      return null
    }
  },

  created() {
    // 初始化级联分类
    this.getCateList()
  },

  methods: {
    // 获取级联分类列表
    async getCateList() {
      const result = await reqParentCateList(3)
      // console.log(result.data)
      this.parentCateData = result.data
    },

    // 级联选择
    cascaderChange() {
      // console.log(this.cascaderValue)
      // console.log(this.cateId)
      this.goodsForm.pCategoryId = this.cateId
    },

    // 准备切换Tab的时候
    beforeLeaveTab(activeName, oldActiveName) {
      // 在一级Tab，并且没有选择商品分类
      if (oldActiveName === '0' && this.cascaderValue.length !== 3) {
        this.$message.error('请选择商品分类！')
        return false
      }
    },

    // tab切换的时候
    async goodsTabClick() {
      if (this.activeIndex === '1' || this.activeIndex === '2') {
        let result
        if (this.activeIndex === '1') {
          // 动态参数
          result = await reqCateParams(this.cateId, 'many')
        } else if (this.activeIndex === '2') {
          // 静态属性
          result = await reqCateParams(this.cateId, 'only')
        }
        if (result.code === 200) {
          // 重新设置一个标签数组
          result.data.forEach(item => {
            const arr1 = []
            const arr2 = []
            item.attr_vals.forEach(item2 => {
              arr1.push(item2.tag_id)
              arr2.push(item2.attr_val)
            })
            item.attrTagIds = arr1
            item.attrVals = arr2
          })
          if (this.activeIndex === '1') {
            this.manyTableData = result.data
          } else {
            this.onlyTableData = result.data
          }
          // console.log(result.data)
        } else {
          this.$message.error('获取商品参数失败！')
        }
      }
    },

    // 图片移除
    handleRemove(file) {
      console.log(file)
      // 获取移除的路径
      const fileName = file.response.data.name
      // 从图片数组中找到对应索引
      const imgList = this.goodsForm.imgsList
      const i = imgList.findIndex(x => x === fileName)
      // 调用splice方法，把图片移除
      imgList.splice(i, 1)
    },

    // 图片预览
    handlePreview(file) {
      this.previewVisible = true
      this.previewURL = file.response.data.url
    },

    // 图片上传成功
    uploadSuccess(response) {
      this.goodsForm.imgsList.push(response.data.name)
    },

    // 添加商品
    addGoods() {
      this.$refs.goodsRef.validate(async valid => {
        if (!valid) {
          this.$message.error('请填写必要的表单项！')
          return
        }
        // 添加表单操作
        const result = await reqAddGoods(this.goodsForm)
        if (result.code === 200) {
          this.$message.success('添加商品成功！')
          this.$router.push('/products')
        }
      })
    }
  }
}
</script>
<style lang='less' scoped>
.el-checkbox {
  margin: 0 10px 10px 0;
}
.el-dialog img {
  width: 100%;
}
.add-btn {
  margin-top: 15px;
}
</style>
